<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/9 0009
 * Time: 14:54
 */

namespace app\general\controller;


use app\common\model\SqArticleAdNodeList;
use app\common\model\SqJinzhu;
use app\common\model\SqMoney;
use app\common\model\SqNotice;
use app\common\MoneyType;
use app\common\pay\wechat\RedPackStatus;
use app\common\Redis;
use app\general\model\SqArticle;
use app\general\model\SqArticleAdNodePayLog;
use app\general\model\SqMessageMoney;
use app\general\model\SqNodeSet;
use app\general\model\SqRedPocket;
use think\Controller;
use think\Db;

class Timers extends Controller
{
    //文章发布七天，若红包未领完，执行退款
    public function timerArticleWithdrawal()
    {
        set_time_limit(0);
        $id = $this->recordTimers(1);
        $res = (new SqRedPocket())->timerArticleWithdrawal();
        $this->updateTimerType($id,$res);
        return $res;
    }

    //每10分钟，增加一次阅读记录·
    public function addArticleReaderNumber()
    {
        set_time_limit(0);
        $id = $this->recordTimers(2);
        $res = (new SqArticle())->addArticleReaderNumber();
        $this->updateTimerType($id,$res);
        return $res;
    }

    //每30分钟，核实一次会员开通付款状态,未付款，账户自动过期
    public function checkMemberPayStatus()
    {
        set_time_limit(0);
        $id = $this->recordTimers(4);
        //获取过期时间小于当前时间且大于0的金主手机号
        $mobile_jinzhu = db('sq_jinzhu')->where(['ex_expiration_time'=>['between', [1, time()]] , 'admin_user_id'=>['>',0]])->column('mobile');
        if(empty($mobile_jinzhu)){
            $this->updateTimerType($id, 'nothing to do');
            return 'nothing to do';
        }

        $where_order = [
            'status' => 1,
            'type' => 1,
            'create_time' => ['>', time()-24*60*60],
            'mobile' => ['in', $mobile_jinzhu]
        ];
        $mobile_order = db('sq_customer_order')->where($where_order)->column('mobile');
        //已打款用户
        if($mobile_order){
            $mobile_jinzhu = array_diff($mobile_jinzhu, $mobile_order);
            db('sq_jinzhu')->where('mobile', 'in', $mobile_order)->update(['ex_expiration_time' => 0]);
        }

        //未打款用户
        if($mobile_jinzhu) {
            db('sq_jinzhu')->where('mobile', 'in', $mobile_jinzhu)->update(['ex_expiration_time'=>0, 'expiration_time'=>time()-1]);
            $this->updateTimerType($id, json_encode($mobile_jinzhu));
        }else{
            $this->updateTimerType($id, 'success');
        }

        return 'success';
    }

    //记录定时器调用时间
    public function recordTimers($type)
    {
        $data = [
            'type' => $type,
            'create_time' => time(),
            'status' => 0
        ];
        return db('sq_record_timer')->insertGetId($data);
    }

    public function updateTimerType($id,$remark='')
    {
        db('sq_record_timer')->where('id', $id)->update(['status'=>1, 'remark'=>$remark]);
    }
    /**
     * 查询红包的状态
     */
    public function searchRedPackageStatus(){
        $where=array(
            "is_get"=>0,
            "mch_billno"=>array("neq",0)
        );
        $list=Db::table("xys_sq_touch_up")->where($where)->select();
        $id = $this->recordTimers(8);
        foreach ($list as $l){
            $data["mch_billno"]=$l["mch_billno"];
            $result=(new RedPackStatus())->pay($data);
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                //判断红包的状态//SENDING:发放中// SENT:已发放待领取// FAILED：发放失败// RECEIVED:已领取// RFUND_ING:退款中// REFUND:已退款
                if($result['status']=='RECEIVED'){//已领取
                    $time=$result['hblist']['hbinfo']['rcv_time'];
                    $message="您在".$result['send_time']."发送的触达红包在".$time."被领取";
                    Db::startTrans();
                    $flag=Db::table("xys_sq_touch_up")->where("id",$l['id'])->update(['is_get'=>1]);
                    if($flag){
                        //推送信息
                        $type=14;
                        (new SqNotice())->saveNoticePush($l['sq_jinzhu_id'], $type, $message);
                        Db::commit();
                    }else{
                        Db::rollback();
                    }
                }else if($result['status']=='REFUND'){//已退款
                    Db::startTrans();
                    $time=$result['refund_time'];
                    $message="您在".$result['send_time']."发送的触达红包在".$time."被退款";
                    //添加资金流水
                    $type = MoneyType::RED_ENVELOPE_FEFUND;   //红包触达
                    $code = date('YmdHis') . mt_rand(1000000, 9999999);
                    (new SqMoney())->addRecord($code, $l["sq_jinzhu_id"], $l["money"], $type, 0, 1);
                    //要给金主加余额
                    Db::table("xys_sq_jinzhu")->where("id",$l["sq_jinzhu_id"])->setInc("current_money",$l["money"]);
                    $flag=Db::table("xys_sq_touch_up")->where("id",$l['id'])->update(['is_get'=>2]);
                    if($flag){
                        //推送信息
                        (new SqNotice())->saveNoticePush($l['sq_jinzhu_id'], $type, $message);
                        Db::commit();
                    }else{
                        Db::rollback();
                    }
                }
            }
        }
        $this->updateTimerType($id,"查询红包领取状态操作完成");
        echo "完成";
    }
    /**
     * 广告佣金发放
     */
    public function sendCommisson(){
        //获取广告id
        $where['end_time']=array('egt',time());
        $where['type']=2;
        $list=(new SqArticleAdNodeList())->field("id,commisson")->where($where)->select();
        if(count($list)<1){
            return "暂无任务";
        }
        $sqArticle=new SqArticle();
        $setInfo=(new SqNodeSet())->field("reward_num,max_price,collect_rate,collect_reae,read_num")->where("id",1)->find();
        $sqArticleAdNodePayLog=new SqArticleAdNodePayLog();
        $sqJinzhu=new SqJinzhu();
        $sqMessageMoney=new SqMessageMoney();
        $redis=Redis::getInstance();
        $sqMoney=new SqMoney();
        $id = $this->recordTimers(9);
        $log=[];
        $data=[];
        foreach($list as $l){
            $key="ad_".$l['id'];
            $arts=$redis->zrangebyscore($key,($setInfo['read_num']+1),"+inf");
           foreach($arts as $a){
                $id=str_replace("art_",'',$a);
                $artInfo=$sqArticle->field("id,sq_jinzhu_id,title,sq_article_hot_id,url_info")->where("id",$id)->find();
                //进行佣金发放
                //1.判读该用户是否已经获取该广告奖励次数sq_article_ad_node_pay_log
                $condition=array(
                    "sq_art_user_id"=>$artInfo['sq_jinzhu_id'],
                    "node_id"=>$l['id'],
                    "is_pay"=>1
                );
                $reward_num=$sqArticleAdNodePayLog->where($condition)->count();
                //获取广告已经发放的的佣金金额
                unset($condition['sq_art_user_id']);
                $use_commisson=$sqArticleAdNodePayLog->where($condition)->sum("total_price");
                //剩余佣金
                $less_commisson=$l['commisson']-$use_commisson;
                //获取该笔的佣金奖励数额
                $reward_commisson=$this->getArtCommisson($artInfo,$setInfo);
                //佣金不足或者奖励次数不足,清除key并继续
                if(($less_commisson<$reward_commisson)||($reward_num>=$setInfo['reward_num'])){
                    //然后清除redis的key
                    $redis->zrem($key,$a);
                    continue;
                }
                //发放佣金
                $price=$sqJinzhu->where("id",$artInfo['sq_jinzhu_id'])->value('current_money');
                $sqJinzhu->startTrans();
                $flag=$sqJinzhu->save(['current_money'=>($price+$reward_commisson)],['id'=>$artInfo['sq_jinzhu_id']]);
                if($flag){//说明发放成功成功
                    //1.消息记录表
                    $log[]=array(
                        "sq_jinzhu_id"=>$artInfo['sq_jinzhu_id'],
                        "money"=>$reward_commisson,
                        "status"=>'已发放到账号余额',
                        "pay_style"=>1,
                        "genre"=>21,
                        "source"=>$artInfo['title'],
                        "time"=>time()
                    );
                    //2.资金流水表
                    $type = MoneyType::AD_COMMISSON;
                    $code = date('YmdHis') . mt_rand(1000000, 9999999);
                    $sqMoney->addRecord($code, $artInfo['sq_jinzhu_id'], $reward_commisson, $type,1, 1);
                    //3.广告支付表
                    $data[]=array(
                        "sq_art_user_id"=>$artInfo['sq_jinzhu_id'],
                        "sq_art_id"=>$artInfo['id'],
                        "title"=>(empty($artInfo['title']))?'':$artInfo['title'],
                        "total_price"=>$reward_commisson,
                        "unit_price"=>$reward_commisson,
                        "pv"=>$setInfo['read_num'],
                        "is_pay"=>1,
                        "create_time"=>time(),
                        "remark"=>'数据达标,佣金正常发放',
                        "node_id"=>$l['id']
                    );
                    $sqJinzhu->commit();
                    //然后清除redis的key
                    //$redis->zrem($key,$a);
                }else{
                    $sqJinzhu->rollback();
                }
            }
        }
        $sqMessageMoney->saveAll($log);
        $sqArticleAdNodePayLog->saveAll($data);
        $this->updateTimerType($id,"广告佣金方法成功");
        return "结束";
    }

    /**
     * 获取文章的佣金
     * @param $artInfo
     * @param $setInfo
     * @return float
     */
    public function getArtCommisson($artInfo,$setInfo){
        if(!empty($artInfo['url_info'])){
            return ($setInfo['max_price']*$setInfo["collect_reae"])/100;
        }else if($artInfo['sq_article_hot_id']!=0){
            return ($setInfo['max_price']*$setInfo["collect_rate"])/100;
        }else{
            return $setInfo['max_price'];
        }
    }

}









